package com.bill99.testmp.testmanage.domain.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.bill99.riaframework.common.dto.TaEmailDto;
import com.bill99.riaframework.common.utils.StringUtil;
import com.bill99.riaframework.domain.mail.EmailSender;
import com.bill99.rmca.common.util.DateUtil;
import com.bill99.testmp.testmanage.common.dto.SysSwitchDto;
import com.bill99.testmp.testmanage.common.dto.TaResultDto;
import com.bill99.testmp.testmanage.common.dto.TaTaskMethodResultDto;
import com.bill99.testmp.testmanage.domain.TaTaskNotifier;
import com.bill99.testmp.testmanage.orm.ibatis.dto.TestProjectDto;
import com.bill99.testmp.testmanage.orm.manager.JiraMng;
import com.bill99.testmp.testmanage.orm.manager.TaMng;

public class TaTaskNotifierImpl implements TaTaskNotifier {

	private TaMng taMng;
	private EmailSender outMailSender;
	private JiraMng jiraMng;

	public void setJiraMng(JiraMng jiraMng) {
		this.jiraMng = jiraMng;
	}

	public void setTaMng(TaMng taMng) {
		this.taMng = taMng;
	}

	public void setOutMailSender(EmailSender outMailSender) {
		this.outMailSender = outMailSender;
	}

	public void taTaskEmailReport(String taTaskId, Long planStepId, Long testProjectId) {
		TestProjectDto testProjectDto = taMng.findTestProjectById(testProjectId);

		BigDecimal errorCount = new BigDecimal(taMng.getTcStatusCounts(taTaskId, planStepId, "0"));
		BigDecimal successCount = new BigDecimal(taMng.getTcStatusCounts(taTaskId, planStepId, "1"));
		BigDecimal con = new BigDecimal(100);
		BigDecimal sumCount = errorCount.add(successCount);

		if (sumCount.equals(BigDecimal.ZERO)) {
			return;
		}

		BigDecimal successsCale = (successCount.divide(sumCount, 2, BigDecimal.ROUND_HALF_EVEN)).multiply(con);
		if (testProjectDto == null) {
			return;
		}

		SysSwitchDto sysSwitchDto = taMng.getSysSwitch();

		TaEmailDto currentUser = taMng.findCurrentUserByTaTask(taTaskId);
        Long tab=taMng.findTab(currentUser.getProjectId());

				List<String> recvEmailAddress = initRecvEmailAddress(testProjectDto.getTeemId(), null, sysSwitchDto);
				if (currentUser != null) {
					recvEmailAddress.add(currentUser.getCurrentUser() + "@99bill.com");
				}
				if (recvEmailAddress == null || recvEmailAddress.size() == 0) {
					return;
				}

		Map<String, List<TaResultDto>> taResultMap = new HashMap<String, List<TaResultDto>>();
		Map<String, List<TaTaskMethodResultDto>> taTaskMethodResultMap = new HashMap<String, List<TaTaskMethodResultDto>>();

		List<TaTaskMethodResultDto> taTaskMethodResultDtos = taMng.getTaTaskMethodResult(taTaskId, planStepId);

		if (taTaskMethodResultDtos != null) {
			List<TaResultDto> taResults = null;
			List<TaResultDto> taResultTmps = null;
			List<TaTaskMethodResultDto> taTaskMethodResults = null;
			for (TaTaskMethodResultDto taTaskMethodResultDto : taTaskMethodResultDtos) {

				String key = taTaskMethodResultDto.getClassName() + taTaskMethodResultDto.getMethodName();
				if (taResultMap.get(key) != null) {
					taResults = taResultMap.get(key);
				} else {
					taResults = new ArrayList<TaResultDto>();
					taResultTmps = taMng.getTaResult(taTaskMethodResultDto.getIdTaTask(), taTaskMethodResultDto.getIdSvnMethod());
					if (taResultTmps != null) {
						taResults.addAll(taResultTmps);
					}
				}
				taResultMap.put(key, taResults);

				// 大集合
				if (taTaskMethodResultMap.get(key) != null) {
					taTaskMethodResults = taTaskMethodResultMap.get(key);
				} else {
					taTaskMethodResults = new ArrayList<TaTaskMethodResultDto>();
				}
				taTaskMethodResults.add(taTaskMethodResultDto);
				taTaskMethodResultMap.put(key, taTaskMethodResults);
			}

			String emailContextStr = buildEmailContext(taResultMap, taTaskMethodResultMap, errorCount, successCount, sumCount, successsCale);

			List<String> ccAddress = sysSwitchDto.getNotifyTaCcaddress() == null ? new ArrayList<String>() : Arrays.asList(sysSwitchDto.getNotifyTaCcaddress().split(","));

			if (!StringUtils.hasLength(emailContextStr)) {
				return;
			}
//			List<String> recvEmailAddress = new ArrayList<String>();
//			ccAddress = new ArrayList<String>();
//			recvEmailAddress.add("lory.shi@99bill.com");
//			if (currentUser != null) {
//				recvEmailAddress.add(currentUser.getCurrentUser() + "@99bill.com");
//			}

			try {
				if (tab>0) {
					outMailSender.sendEmail(recvEmailAddress, ccAddress, "【自动化测试结果通知】【" + testProjectDto.getProjectname() + "】" + "【" + currentUser.getUnitType() + "环境】" + "【"
							+ DateUtil.getDate() + "】", emailContextStr, "poa_qa_tp@99bill.com");

				} else {
					outMailSender.sendEmail(recvEmailAddress, ccAddress, "【自动化测试结果通知】【" + testProjectDto.getProjectname() + "】" + "【" + DateUtil.getDate() + "】", emailContextStr,
							"poa_qa_tp@99bill.com");

				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	private String buildEmailContext(Map<String, List<TaResultDto>> taResultMap, Map<String, List<TaTaskMethodResultDto>> taTaskMethodResultMap, BigDecimal errorCount,
			BigDecimal successCount, BigDecimal sumCount, BigDecimal successsCale) {
		StringBuilder contentSb = new StringBuilder();

		contentSb.append("<style>    ");
		contentSb.append("/* Changing the layout to use less space for mobiles */                         ");
		contentSb
				.append("@media screen and (max-device-width: 480px), screen and (-webkit-min-device-pixel-ratio: 2) {                                                             ");
		contentSb.append(" #email-body {                                                                  ");
		contentSb.append("min-width: 30em !important;                                                     ");
		contentSb.append("}          ");
		contentSb.append(" #email-page {                                                                  ");
		contentSb.append("padding: 8px !important;                                                        ");
		contentSb.append("}          ");
		contentSb.append(" #email-banner {                                                                ");
		contentSb.append("padding: 8px 8px 0 8px !important;                                              ");
		contentSb.append("}          ");
		contentSb.append(" #email-avatar {                                                                ");
		contentSb.append("margin: 1px 8px 8px 0 !important;                                               ");
		contentSb.append("padding: 0 !important;                                                          ");
		contentSb.append("}          ");
		contentSb.append(" #email-fields {                                                                ");
		contentSb.append("padding: 0 8px 8px 8px !important;                                              ");
		contentSb.append("}          ");
		contentSb.append(" #email-gutter {                                                                ");
		contentSb.append("width: 0 !important;                                                            ");
		contentSb.append("}          ");
		contentSb.append("}          ");
		contentSb.append("</style>   ");
		// ///////////////////////////////////////////////////////////////
		contentSb
				.append("  <table id=\"email-wrap\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color:#f0f0f0;color:#000000;width:100%;\">");
		contentSb.append("    <tr valign=\"top\">");
		contentSb
				.append("      <td id=\"email-page\" style=\"padding:16px !important;\"><table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color:#ffffff;border:1px solid #bbbbbb;color:#000000;width:100%;\"> ");
		contentSb.append("          <tr valign=\"top\">");
		contentSb
				.append("            <td bgcolor=\"#003366\" style=\"background-color:#003366;color:#ffffff;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;line-height:1;\">自动化测试结果统计</td>                                           ");
		contentSb.append("          </tr>");
		contentSb.append("          <tr valign=\"top\">");
		contentSb
				.append("            <td id=\"email-fields\" style=\"padding:10px 10px 10px 10px;\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"padding:0;text-align:left;width:100%;\" width=\"100%\">                             ");
		contentSb.append("                <tr valign=\"top\">");
		contentSb.append("                  <td><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
		contentSb.append("                      <tr valign=\"top\">");

		contentSb.append("<td width=\"10%\" style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 0 10px 0;\"><strong>用例总数:" + sumCount
				+ "</strong></td>");
		contentSb.append("<td width=\"10%\" style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 0 10px 0;\"><strong>成功数:" + successCount
				+ "</strong></td>");
		contentSb.append("<td width=\"10%\" style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 0 10px 0;\"><strong>失败数:" + errorCount
				+ "</strong></td>");
		contentSb.append("<td style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 10px 10px 0;white-space:nowrap;\"><strong>成功比例:"
				+ successsCale + "%</strong></td>");

		contentSb.append("                      </tr>");
		contentSb.append("</table>");
		contentSb.append("</table>");
		contentSb.append("</table>");

		// ///////////////////////////////////////////////////////////////
		contentSb.append("<div id=\"email-body\">");

		contentSb
				.append("  <table id=\"email-wrap\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color:#f0f0f0;color:#000000;width:100%;\">");
		contentSb.append("    <tr valign=\"top\">");
		contentSb
				.append("      <td id=\"email-page\" style=\"padding:16px !important;\"><table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color:#ffffff;border:1px solid #bbbbbb;color:#000000;width:100%;\"> ");
		contentSb.append("          <tr valign=\"top\">");
		contentSb
				.append("            <td bgcolor=\"#003366\" style=\"background-color:#003366;color:#ffffff;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;line-height:1;\">自动化测试结果明细</td>                                           ");
		contentSb.append("          </tr>");
		contentSb.append("          <tr valign=\"top\">");
		contentSb
				.append("            <td id=\"email-fields\" style=\"padding:10px 10px 10px 10px;\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"padding:0;text-align:left;width:100%;\" width=\"100%\">                             ");
		contentSb.append("                <tr valign=\"top\">");
		contentSb.append("                  <td><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
		contentSb.append("                      <tr valign=\"top\">");

		contentSb
				.append("<td width=\"50%\" style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 10px 10px 0;white-space:nowrap;\"><strong>用例名</strong></td>");
		contentSb.append("<td width=\"10%\" style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 0 10px 0;\"><strong>结果</strong></td>");
		contentSb.append("<td width=\"30%\" style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 0 10px 0;\"><strong>方法描述</strong></td>");
		contentSb
				.append("<td width=\"10%\" style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 0 10px 0;\"><strong>耗时(S)</strong></td>");
		// contentSb.append("<td style=\"color:#000000;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;padding:0 0 10px 0;\"><strong>日志</strong></td>");

		contentSb.append("                      </tr>");

		for (String key : taTaskMethodResultMap.keySet()) {

			List<TaTaskMethodResultDto> taTaskMethodResultDtos = taTaskMethodResultMap.get(key);
			TaTaskMethodResultDto taTaskMethodResult = taTaskMethodResultDtos.get(0);
			int x = 0;
			for (TaTaskMethodResultDto taTaskMethodResultDto : taTaskMethodResultDtos) {
				contentSb.append("<tr>");
				contentSb
						.append("<td style=\"border:solid #add9c0; border-width:0px 1px 1px 0px; padding:10px 0px;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px; \" >");
				contentSb.append(taTaskMethodResultDto.getTestCaseName());
				contentSb.append("</td>");
				// contentSb.append();

				if (x == 0) {
					contentSb.append("<td  rowspan=\"" + taTaskMethodResultDtos.size() + "\""
					// + " title=\"" + taTaskMethodResult.getErrorMsg()+"\""
							+ "style=\"border:solid #add9c0; border-width:0px 1px 1px 0px; padding:10px 0px;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px; \" >");
					if (taTaskMethodResult.getState()) {
						contentSb.append("<span style=\"color: green\">成功</span>");
					} else {
						contentSb.append("<span style=\"color: red\">失败</span>");
					}
					contentSb.append("</td>");

					contentSb
							.append("<td  rowspan=\""
									+ taTaskMethodResultDtos.size()
									+ "\"style=\"border:solid #add9c0; border-width:0px 1px 1px 0px; padding:10px 0px;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px; \" >");
					contentSb.append(taTaskMethodResult.getClassName() + "</ br>");
					contentSb.append(taTaskMethodResult.getMethodName() + "</ br>");
					contentSb.append(taTaskMethodResult.getMethodMemo() + "</ br>");
					contentSb.append("</td>");

					contentSb
							.append("<td  rowspan=\""
									+ taTaskMethodResultDtos.size()
									+ "\"  style=\"border:solid #add9c0; border-width:0px 1px 1px 0px; padding:10px 0px;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px; \">");
					if (taTaskMethodResult.getCostMillis() != null) {
						contentSb.append(taTaskMethodResult.getCostMillis().longValue() / 1000);
					}
					contentSb.append("</td>");

					// contentSb.append("<td  rowspan=\"" + taTaskMethodResultDtos.size() +
					// "\" style=\"border:solid #add9c0; border-width:0px 1px 1px 0px; padding:10px 0px;\">");
					//
					// contentSb.append("<table>");
					//
					// List<TaResultDto> taResultDtos = taResultMap.get(key);
					// if (taResultMap.size() > 0 && taResultDtos != null && taResultDtos.size() > 0) {
					// for (TaResultDto taResultDto : taResultDtos) {
					// contentSb.append("<tr><td style=\" font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:12px;\" >" + taResultDto.getMemo()
					// + "</td></tr>");
					// }
					// }
					// contentSb.append("</table>");
					//
					// contentSb.append("</td>");

				}

				contentSb.append("</tr>");
				x++;
			}

		}

		contentSb.append("                    </table></td>                                               ");
		contentSb.append("                </tr>                                                           ");
		contentSb.append("              </table></td>                                                     ");
		contentSb.append("          </tr>                                                                 ");
		contentSb.append("        </table></td>                                                           ");
		contentSb.append("      <!-- End #email-page -->                                                  ");
		contentSb.append("    </tr>  ");
		contentSb.append("    <tr valign=\"top\">                                                         ");
		contentSb
				.append("      <td style=\"color:#505050;font-family:Arial,FreeSans,Helvetica,sans-serif;font-size:10px;line-height:14px;padding: 0 16px 16px 16px;text-align:center;\"> 此邮件由测试管理平台自动发送.<br />                            ");
		contentSb.append("        如果你认为这封邮件不正确, 请联系 <a style='color:#326ca6;' href='mailto:poa_qa_tp@99bill.com'>系统管理员</a>。</td>                               ");
		contentSb.append("    </tr>  ");
		contentSb.append("  </table> ");
		contentSb.append("  <!-- End #email-wrap -->                                                      ");
		contentSb.append("</div>     ");
		contentSb.append("<!-- End #email-body -->                                                        ");

		return contentSb.toString();

	}

	// 获取邮箱列表
	private List<String> initRecvEmailAddress(Long teemId, Long issueId, SysSwitchDto sysSwitchDto) {
		if (sysSwitchDto == null || sysSwitchDto.getNotifyTaState() == null || !sysSwitchDto.getNotifyTaState()) {
			return null;
		}

		List<String> emailList = new ArrayList<String>();

		if (StringUtils.hasLength(sysSwitchDto.getNotifyTaRecvaddress())) {
			emailList = jiraMng.getEmail4RoleIssue(StringUtil.string2LongArray(sysSwitchDto.getNotifyTaRecvaddress()), issueId);
		}
		if (StringUtils.hasLength(sysSwitchDto.getNotifyTaRecvaddress())) {
			emailList.addAll(jiraMng.getEmail4Role(StringUtil.string2LongArray(sysSwitchDto.getNotifyTaRecvaddress()), new Long[] { teemId }));
		} else if (StringUtils.hasLength(sysSwitchDto.getNotifyTaCcaddress())) {
			emailList.addAll(Arrays.asList(sysSwitchDto.getNotifyTaCcaddress().split(",")));
		}
		return emailList;

	}
}
